package pers.cj.pdos.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.excel.ExcelSale;
import pers.cj.pdos.service.*;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * <p>
 * 当销售单产生后，订单会进入待出库状态，需要仓库管理员进行出库操作 前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/sale")
public class SaleController extends BaseController {
    @Autowired
    ISaleService saleService;
    @Autowired
    IGoodsStockService goodsStockService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    IPacketService packetService;
    @Autowired
    IPacketGoodsService packetGoodsService;
    @Autowired
    IHouseOutService houseOutService;
    @Autowired
    IHouseOutGoodsService houseOutGoodsService;
    @Autowired
    IHouseOutPacketService houseOutPacketService;

    @RequiresPermissions("sale:query")
    @RequestMapping("/sale")
    public String sale(Model model){
        model.addAttribute(getBusinessSet());
        return "/sale/sale";
    }


    @RequiresPermissions("sale:insert")
    @RequestMapping("/saleNew")
    public String saleNew(){
        return "/sale/saleNew";
    }

    @RequiresPermissions("sale:insert")
    @RequestMapping("/saleNewBySaleOrder")
    public String saleNewBySaleOrder(Model model,String saleOrderId){
        model.addAttribute("saleOrderId",saleOrderId);
        return "/sale/saleNewBySaleOrder";
    }

    @RequiresPermissions("sale:insert")
    @RequestMapping("/saleNewByBorrowOut")
    public String saleNewByBorrowOut(Model model, String borrowOutId){
        model.addAttribute("borrowOutId", borrowOutId);
        return "/sale/saleNewByBorrowOut";
    }

    @RequiresPermissions("sale:query")
    @RequestMapping("/saleDetail")
    public String saleDetail(Model model, String id){
        model.addAttribute("id",id);
        return "/sale/saleDetail";
    }

    @ResponseBody
    @RequestMapping("/sale/getListForSelect")
    public ResponseList getListForSelect(int page, int limit, String search,String storeId){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();

        List<SaleVo> list = saleService.listVoForSelect(company.getId(),
                page,
                limit,
                Utils.genLikeData(search),
                storeId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,null));
        long count = saleService.countForSelect(company.getId(),
                Utils.genLikeData(search),
                storeId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,null));
        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequestMapping("/sale/getList")
    public ResponseList getList(int page,
                                int limit,
                                String close,
                                String search,
                                String no,
                                String goodsName,
                                String remark,
                                String storeId,
                                String houseId,
                                String settAccountId,
                                String custom,
                                String deliveryDate1,
                                String deliveryDate2,
                                String makeTime1,
                                String makeTime2,
                                String userId,
                                String date1,
                                String date2,
                                String date,
                                String makeUserId,
                                String customId,
                                String status){
        Company company = getCompany();

        UserVo userVo = getLoginUserVo();
        List<SaleVo> saleVoList = saleService.listVo(company.getId(),
                page,
                limit,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                storeId,
                houseId,
                settAccountId,
                Utils.genLikeData(custom),
                Utils.genDate(deliveryDate1),
                Utils.genDate(deliveryDate2),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                PdosUtils.getViewOrderStoreId(userVo, null),
                PdosUtils.getViewOrderUserId(userVo, userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genDate(date),
                makeUserId,
                customId,
                Utils.genInteger(status));
        long count = saleService.count(company.getId(),
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                storeId,
                houseId,
                settAccountId,
                Utils.genLikeData(custom),
                Utils.genDate(deliveryDate1),
                Utils.genDate(deliveryDate2),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                PdosUtils.getViewOrderStoreId(userVo, null),
                PdosUtils.getViewOrderUserId(userVo, userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genDate(date),
                makeUserId,
                customId,
                Utils.genInteger(status));
        return ResponseList.success(count,saleVoList);
    }


    @ResponseBody
    @RequiresPermissions("sale:insert")
    @RequestMapping("/sale/add")
    public ResponseData add(@RequestBody SaleVo saleVo){

        Company company = getCompany();
        BusinessSet businessSet = getBusinessSet();

        if (Utils.isEmpty(saleVo.getNo())){
            return ResponseData.fail("编号不能为空");
        }

        if (Utils.isEmpty(saleVo.getSaleGoodsVoList()) && Utils.isEmpty(saleVo.getSalePacketVoList())){
            return ResponseData.fail("您未选择任何商品");
        }

        if (saleVo.getDate() == null){
            return ResponseData.fail("业务日期不能为空");
        }

        if (saleService.checkNo(saleVo.getNo(),company.getId())){
            return ResponseData.fail("编号已被使用");
        }

        if (saleVo.getTotalAmt().compareTo(saleVo.getRealAmt()) == -1){
            return ResponseData.fail("应收金额不能大于总计金额");
        }

        if (getHouseLocking(saleVo.getHouseId())) {
            return ResponseData.fail("仓库被锁定，请更换仓库");
        }

        GoodsUtil goodsUtil = new GoodsUtil(saleVo.getHouseId(),saleVo.getSaleGoodsVoList(),saleVo.getSalePacketVoList());
        if (!PdosUtils.houseInOut(businessSet) && !PdosUtils.negativeSale(businessSet)) {
            //未启用出入库管理，会直接进行出库操作，所以要进行库存的比对
            String msg = goodsUtil.checkStock();
            if (msg!=null){
                return ResponseData.fail(msg);
            }
        }

        //准备插入数据库的数据
        Sale sale = DataUtil.genEntityFromVo(Sale.class, saleVo);
        DataUtil.processEntity(company,sale);
        if (!PdosUtils.houseInOut(businessSet)) {
            sale.setStatus(1);
        }else{
            sale.setStatus(2);
        }
        sale.setRetail(false);
        sale.setRefund(0);
        sale.setMakeUserId(getLoginUserId());
        sale.setMakeTime(new Date());
        sale.setClose(false);
        if (Utils.isEmpty(sale.getSaleOrderId())) {
            sale.setSaleOrderId(null);
        }

        BigDecimal totalAmount = goodsUtil.getTotalAmount();
        if (sale.getDiscountFlag() == 1) {
            sale.setAfterDiscountAmt(totalAmount.multiply(sale.getDiscountRate()).divide(new BigDecimal(100)));
            sale.setDiscountAmt(totalAmount.subtract(sale.getAfterDiscountAmt())); //折扣金额 = 总金额- 折后金额
        } else {
            sale.setAfterDiscountAmt(totalAmount.subtract(sale.getDiscountAmt()));
            sale.setDiscountRate(new BigDecimal(100).multiply(sale.getAfterDiscountAmt()).divide(totalAmount,4, RoundingMode.HALF_UP)); //折扣率 = 100*折后金额 / 总金额
        }

        if(!PdosUtils.saleTaxRateFlag(businessSet)) {
            sale.setTax(new BigDecimal(0));
        } else {
            sale.setTax(sale.getAfterDiscountAmt().multiply(PdosUtils.saleTaxRate(businessSet)));
        }

        Map<String,BigDecimal> costMap = genCostMap(goodsUtil);


        BigDecimal profits = new BigDecimal(0);//销售单的毛利
        List<SaleGoods> saleGoodsList = new ArrayList<>();
        List<GoodsSn> goodsSnList = new ArrayList<>();
        List<GoodsSnLog> goodsSnLogList = new ArrayList<>();

        if (!Utils.isEmpty(saleVo.getSaleGoodsVoList())) {
            for (SaleGoodsVo vo : saleVo.getSaleGoodsVoList()) {
                SaleGoods entity = DataUtil.genEntityFromVo(SaleGoods.class, vo);
                DataUtil.processEntity(company, entity);
                entity.setSaleId(sale.getId());
                entity.setRefundNumber(new BigDecimal(0));

                BigDecimal cost = costMap.containsKey(entity.getGoodsId()) ? costMap.get(entity.getGoodsId()) : new BigDecimal(0);
                cost = cost.multiply(entity.getNumber()).multiply(entity.getTimes());//该商品的成本

                entity.setAfterDiscountAmt(entity.getAmount().multiply(sale.getDiscountRate()).divide(new BigDecimal(100)));//折后金额 = 金额 * 折扣率 / 100
                entity.setProfits(entity.getAfterDiscountAmt().subtract(cost));//该商品的毛利 = 折后的商品金额-成本
                if(!PdosUtils.saleTaxRateFlag(businessSet)) {
                    entity.setTax(new BigDecimal(0));
                } else {
                    entity.setTax(entity.getAfterDiscountAmt().multiply(PdosUtils.saleTaxRate(businessSet)));
                }

                profits = profits.add(entity.getProfits());

                saleGoodsList.add(entity);

                if (!Utils.isEmpty(vo.getGoodsSnList())) {
                    for (GoodsSn goodsSn : vo.getGoodsSnList()) {
                        goodsSnList.add(goodsSn);

                        GoodsSnLog log = new GoodsSnLog();
                        DataUtil.processEntity(company, log);
                        log.setGoodsId(goodsSn.getGoodsId());
                        log.setSn(goodsSn.getSn());
                        log.setType(2);
                        log.setSaleGoodsId(entity.getId());
                        if (!Utils.isEmpty(sale.getBorrowOutId())) {
                            log.setBorrow(1);
                        }
                        goodsSnLogList.add(log);
                    }
                }
            }
        }

        List<SalePacket> salePacketList = new ArrayList<>();
        List<SalePacketGoods> salePacketGoodsList = new ArrayList<>();

        if (!Utils.isEmpty(saleVo.getSalePacketVoList())) {
            for (SalePacketVo vo : saleVo.getSalePacketVoList()) {
                SalePacket entity = DataUtil.genEntityFromVo(SalePacket.class, vo);
                DataUtil.processEntity(company, entity);
                entity.setSaleId(sale.getId());
                entity.setRefundNumber(new BigDecimal(0));
                entity.setAfterDiscountAmt(entity.getAmount().multiply(sale.getDiscountRate()).divide(new BigDecimal(100)));//折后金额 = 金额 * 折扣率 / 100
                if(!PdosUtils.saleTaxRateFlag(businessSet)) {
                    entity.setTax(new BigDecimal(0));
                } else {
                    entity.setTax(entity.getAfterDiscountAmt().multiply(PdosUtils.saleTaxRate(businessSet)));
                }

                BigDecimal price = entity.getAfterDiscountAmt().divide(entity.getNumber(),4, RoundingMode.HALF_UP); // 套餐折后单价

                BigDecimal packet_profits = new BigDecimal(0);//套餐的毛利
                BigDecimal packetGoodsTotal = genPacketTotal(vo);//此套餐的总价，用于下面计算实际金额
                for (SalePacketGoodsVo pgv : vo.getPacketGoodsVoList()) {
                    SalePacketGoods pg = DataUtil.genEntityFromVo(SalePacketGoods.class, pgv);
                    DataUtil.processEntity(company, pg);
                    pg.setSaleId(entity.getSaleId());
                    pg.setSalePacketId(entity.getId());

                    pg.setAfterDiscountAmt(price.multiply(pg.getAmount()).divide(packetGoodsTotal,4, RoundingMode.HALF_UP));//套餐中商品的实际金额（折后换算的金额）
                    if(!PdosUtils.saleTaxRateFlag(businessSet)) {
                        pg.setTax(new BigDecimal(0));
                    } else {
                        pg.setTax(pg.getAfterDiscountAmt().multiply(PdosUtils.saleTaxRate(businessSet)));
                    }

                    BigDecimal cost = costMap.containsKey(pg.getGoodsId()) ? costMap.get(pg.getGoodsId()) : new BigDecimal(0);
                    cost = cost.multiply(pg.getNumber()).multiply(pg.getTimes());//该商品的成本
                    pg.setProfits(pg.getAfterDiscountAmt().subtract(cost));//该商品的毛利 = 折后的商品金额-成本

                    packet_profits = packet_profits.add(pg.getProfits());

                    salePacketGoodsList.add(pg);
                }

                entity.setProfits(packet_profits.multiply(entity.getNumber()));//套餐的总利润，数量*单个套餐利润
                profits = entity.getProfits().add(profits);
                salePacketList.add(entity);
            }
        }

        sale.setProfits(profits);
        saleService.insert(businessSet, sale, saleGoodsList,goodsSnList,goodsSnLogList, salePacketList, salePacketGoodsList);

        SaleVo dbVo = saleService.getVoById(sale.getId());
        if (!Utils.isEmpty(goodsSnList) && PdosUtils.houseInOut(businessSet)  && Utils.isEmpty(sale.getBorrowOutId())) {
            //已启用待出库入管理，但是前台传入了sn号，提示
            return ResponseData.success(dbVo, "处理成功，管理员在您新增单据过程中启用了出入库管理，录入的sn需要在出库时重新选择");
        }
        return ResponseData.success(dbVo);
    }

    @ResponseBody
    @RequiresPermissions("sale:close")
    @RequestMapping("/sale/close")
    public ResponseEntity close(@RequestBody Sale sale){
        //检查是否已经关闭
        if (saleService.checkClose(sale)){
            return ResponseEntity.fail("该单据已被关闭，不能重复关闭");
        }


        if(saleService.getById(sale.getId()).getRefund() !=0) {
            return ResponseEntity.fail("该进货单有退货，建议在作废退货单后才允许作废该进货单。");
        }

        if(houseOutService.checkByLinkId(sale.getId())) {
            return ResponseEntity.fail("该订单存在出库单，请先作废对应的出库单");
        }

        try {
            saleService.close(sale, getBusinessSet());
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("关闭订单失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("sale:insert")
    @RequestMapping("/sale/updateImage")
    public ResponseEntity updateImage(@RequestBody Sale sale){
        try {
            Sale temp = new Sale();
            temp.setId(sale.getId());
            temp.setImage(sale.getImage());
            saleService.updateById(temp);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("更新图片失败");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/sale/uploadImg", method = RequestMethod.POST)
    public ResponseData uploadImg(MultipartFile imageFile) {
        return processUploadImg(imageFile, "sale");
    }

    @ResponseBody
    @RequestMapping("/sale/getVoById.action")
    public ResponseData getVoById(String id){
        if (Utils.isEmpty(id)){
            return ResponseData.fail("id不能为空");
        }

        SaleVo saleVo = saleService.getVoById(id);
        if (saleVo == null) {
            return ResponseData.fail("id不正确");
        }
        return ResponseData.success(saleVo);
    }

    /**
     * 根据获取SaleVo，若其实由出库单出库，则要获取已出库商品的数量
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/sale/getVoByIdWithCanRefundNumber")
    public ResponseData getVoByIdWithCanRefundNumber(String id) {
        SaleVo saleVo = saleService.getVoById(id);
        if (saleVo == null) {
            return ResponseData.fail("未找到单据");
        }

        //获取到此销售单的已经出库的数量
        if (saleVo.getStatus() != 1) {
            //-------------------------商品处理-------------------------------
            if (!Utils.isEmpty(saleVo.getSaleGoodsVoList())) {
                Map<String, BigDecimal> houseOutMap = new HashMap<>();//key-saleGoodsIs value-number
                for (HouseOutGoods houseOutGoods : houseOutGoodsService.listByLinkId(id)) {
                    String saleGoodsId = houseOutGoods.getSaleGoodsId();
                    BigDecimal number = houseOutGoods.getNumber();
                    if (houseOutMap.containsKey(saleGoodsId)) {
                        //若存在，则累加数量
                        houseOutMap.put(saleGoodsId, houseOutMap.get(saleGoodsId).add(number));
                    } else {
                        //不存在，则新建
                        houseOutMap.put(saleGoodsId, number);
                    }
                }

                //新组成的数据
                List<SaleGoodsVo> saleGoodsVoList = new ArrayList<>();
                for (SaleGoodsVo vo : saleVo.getSaleGoodsVoList()) {
                    if (houseOutMap.containsKey(vo.getId())) {
                        //将已存在进货单对应入库单的商品添加到新表，并将数量重新赋值
                        vo.setNumber(houseOutMap.get(vo.getId()));
                        vo.setAmount(vo.getNumber().multiply(vo.getPrice()));//重新计算器总额
                        saleGoodsVoList.add(vo);
                    }
                }
                saleVo.setSaleGoodsVoList(saleGoodsVoList);
            }



            //-------------------------套餐处理-------------------------------
            if (!Utils.isEmpty(saleVo.getSalePacketVoList())) {
                Map<String, BigDecimal> houseOutMap = new HashMap<>();//key-saleGoodsIs value-number
                for (HouseOutPacket houseOutPacket : houseOutPacketService.listByLinkId(id)) {
                    String salePacketId = houseOutPacket.getSalePacketId();
                    BigDecimal number = houseOutPacket.getNumber();
                    if (houseOutMap.containsKey(salePacketId)) {
                        //若存在，则累加数量
                        houseOutMap.put(salePacketId, houseOutMap.get(salePacketId).add(number));
                    } else {
                        //不存在，则新建
                        houseOutMap.put(salePacketId, number);
                    }
                }

                //新组成的数据
                List<SalePacketVo> salePacketVoList = new ArrayList<>();
                for (SalePacketVo vo : saleVo.getSalePacketVoList()) {
                    if (houseOutMap.containsKey(vo.getId())) {
                        //将已存在进货单对应入库单的商品添加到新表，并将数量重新赋值
                        vo.setNumber(houseOutMap.get(vo.getId()));
                        vo.setAmount(vo.getNumber().multiply(vo.getPrice()));//重新计算器总额
                        salePacketVoList.add(vo);
                    }
                }
                saleVo.setSalePacketVoList(salePacketVoList);
            }

        }

        return ResponseData.success(saleVo);
    }


    @ResponseBody
    @RequestMapping("/sale/listVoBySaleOrder")
    public ResponseData listVoBySaleOrder(String saleOrderId) {
        return ResponseData.success(saleService.listVoBySaleOrder(saleOrderId));
    }

    @ResponseBody
    @RequestMapping("/sale/listVoByBorrowOut")
    public ResponseData listVoByBorrowOut(String borrowOutId) {
        return ResponseData.success(saleService.listVoByBorrowOut(borrowOutId));
    }

    @ResponseBody
    @RequestMapping("/sale/listVoByIds")
    public ResponseData listVoByIds(@RequestBody List<String> ids){
        if (Utils.isEmpty(ids)){
            return ResponseData.fail("id不能为空");
        }
        List<SaleVo> list = saleService.listVoByIds(ids);
        if (Utils.isEmpty(list)) {
            return ResponseData.fail("为获取到信息");
        }

        return ResponseData.success(list);
    }

    @ResponseBody
    @RequiresPermissions("sale:export")
    @RequestMapping("/sale/export")
    public ResponseData export(String close,
                               String search,
                               String no,
                               String goodsName,
                               String remark,
                               String storeId,
                               String houseId,
                               String settAccountId,
                               String custom,
                               String deliveryDate1,
                               String deliveryDate2,
                               String makeTime1,
                               String makeTime2,
                               String userId,
                               String date1,
                               String date2,
                               String date,
                               String makeUserId,
                               String customId,
                               String status){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleVo> saleVoList = saleService.listVo(company.getId(),
                null,
                null,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                storeId,
                houseId,
                settAccountId,
                Utils.genLikeData(custom),
                Utils.genDate(deliveryDate1),
                Utils.genDate(deliveryDate2),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                PdosUtils.getViewOrderStoreId(userVo, null),
                PdosUtils.getViewOrderUserId(userVo, userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genDate(date),
                makeUserId,
                customId,
                Utils.genInteger(status));

        String fileName = "销售单列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelSale.class);
            sheet1.setSheetName("销售单信息");
            writer.write(genExcelList(saleVoList), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("销售订单列表导出失败");
        }
    }

    private List<ExcelSale> genExcelList(List<SaleVo> saleVoList) {
        BusinessSet businessSet = getBusinessSet();
        List<ExcelSale> list = new ArrayList<>();
        for (SaleVo vo : saleVoList){
            ExcelSale excel = new ExcelSale();
            excel.setDate(DateUtils.getDate(vo.getDate(), DateUtils.YYYY_MM_DD));
            excel.setDeliveryData(vo.getDeliveryDate()==null ? "": DateUtils.getDate(vo.getDeliveryDate(), DateUtils.YYYY_MM_DD));
            excel.setAddress(vo.getAddress()==null ? "": vo.getAddress());
            excel.setNo(vo.getNo());
            excel.setLinkNo(vo.getSaleOrder()==null ? "": vo.getSaleOrder().getNo());
            excel.setCustomNo(vo.getCustom().getNo());
            excel.setCustomName(vo.getCustom().getName());
            String goods = "";
            BigDecimal number = new BigDecimal(0);
            BigDecimal amount = new BigDecimal(0);
            if (!Utils.isEmpty(vo.getSaleGoodsVoList())) {
                for (SaleGoodsVo saleGoodsVo : vo.getSaleGoodsVoList()) {
                    number = number.add(saleGoodsVo.getNumber());
                    amount = amount.add(saleGoodsVo.getAmount());
                    goods += saleGoodsVo.getGoodsVo().getName() + "、";
                }
            }

            if (!Utils.isEmpty(vo.getSalePacketVoList())) {
                for (SalePacketVo salePacketVo : vo.getSalePacketVoList()) {
                    number = number.add(salePacketVo.getNumber());
                    amount = amount.add(salePacketVo.getAmount());
                    goods += salePacketVo.getPacketName() + "、";
                }
            }

            if (!Utils.isEmpty(goods)) {
                goods = goods.substring(0, goods.length() - 1);
            }
            excel.setGoods(goods);
            excel.setNumber(PdosUtils.getNumber(number,businessSet));
            excel.setOldTotalAmt(PdosUtils.getPrice(amount,businessSet));

            excel.setDiscountAmt(PdosUtils.getPrice(vo.getDiscountAmt(),businessSet));

            excel.setTax(PdosUtils.getPrice(vo.getTax(),businessSet));
            excel.setOtherAmt(PdosUtils.getPrice(vo.getOtherAmt(),businessSet));
            excel.setTotalAmt(PdosUtils.getPrice(vo.getTotalAmt(),businessSet));
            excel.setRealAmt(PdosUtils.getPrice(vo.getRealAmt(),businessSet));
            excel.setUser(vo.getUser().getName());
            excel.setProfits(PdosUtils.getPrice(vo.getProfits(),businessSet));
            excel.setMakeUser(vo.getMakeUser().getName());
            if (vo.getType()==1){
                excel.setType("批发");
            } else {
                excel.setType("零售");
            }
            excel.setStore(vo.getHouseVo().getStore().getName());
            excel.setHouse(vo.getHouseVo().getName());
            excel.setRemark(vo.getRemark());
            if (vo.getTicket() == 1) {
                excel.setTicket("无需开票");
            } else if (vo.getTicket() == 2) {
                excel.setTicket("未开票");
            } else {
                excel.setTicket("已开票");
            }
            excel.setClose(vo.getClose() ? "是":"否");
            list.add(excel);
        }
        return list;
    }

    private BigDecimal genPacketTotal(SalePacketVo vo){
        BigDecimal total = new BigDecimal(0);

        for (SalePacketGoodsVo pgv:vo.getPacketGoodsVoList()) {
            total = total.add(pgv.getAmount());
        }

        return total;
    }
}
